package com.aios.client;

import com.aios.shared.FieldVerifier;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.layout.client.Layout.Alignment;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment.VerticalAlignmentConstant;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.StackPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.youtube.client.YouTubeEmbeddedPlayer;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class AIOS implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);
	
	private static int num = 0;

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		
		final Button sendButton = new Button("Ask");
		// We can add style names to widgets
		sendButton.addStyleName("sendButton");
		
		final TextBox nameField = new TextBox();
		nameField.setWidth("400px");
		nameField.setText("Tell me what you want");
		
		final Label errorLabel = new Label();
		
		final HorizontalPanel askAiosPanel = new HorizontalPanel();
		askAiosPanel.add(nameField);
		askAiosPanel.add(sendButton);
		askAiosPanel.add(errorLabel);
		askAiosPanel.setSpacing(5);
		
		
		// suggestion links panel
		final VerticalPanel suggestionLinlsPanel = new VerticalPanel();
		suggestionLinlsPanel.setSpacing(8);
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		suggestionLinlsPanel.add(new Hyperlink("What's the latest news?", "What's the latest news?"));
		
		// suggestions panel
		final DecoratedStackPanel suggestionsPanel = new DecoratedStackPanel();
		//final StackPanel suggestionsPanel = new StackPanel();
		suggestionsPanel.setWidth("200px");
		suggestionsPanel.add(suggestionLinlsPanel, "Suggestions");
		
		// answers panel
		final VerticalPanel answersPanel = new VerticalPanel();
		answersPanel.setSpacing(20);
		final ScrollPanel scrollPanel = new ScrollPanel(answersPanel);
		scrollPanel.setSize("700px", "450px");
		final DecoratorPanel dP = new DecoratorPanel();
		dP.add(scrollPanel);
		
		// create the mainView
		final DockLayoutPanel mainView = new DockLayoutPanel(Unit.PX);
		
		mainView.addNorth(AIOS.getCenteredHorizontalAlignment(new HTML("<h1>AIOS</h1>"),HasVerticalAlignment.ALIGN_MIDDLE), 100);
		mainView.addEast(AIOS.getCenteredHorizontalAlignment(new HTML("East"),HasVerticalAlignment.ALIGN_MIDDLE), 200);
		mainView.addWest(AIOS.getCenteredHorizontalAlignment(suggestionsPanel,HasVerticalAlignment.ALIGN_TOP), 250);
		mainView.addSouth(AIOS.getCenteredHorizontalAlignment(askAiosPanel,HasVerticalAlignment.ALIGN_MIDDLE), 100);
		mainView.add(AIOS.getCenteredHorizontalAlignment(dP,HasVerticalAlignment.ALIGN_TOP));
		
		

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
//		RootPanel.get("nameFieldContainer").add(nameField);
//		RootPanel.get("sendButtonContainer").add(sendButton);
//		RootPanel.get("errorLabelContainer").add(errorLabel);
		//RootPanel.get("mainDiv").add(mainView);
		RootLayoutPanel.get().add(mainView);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendNameToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendNameToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				String textToServer = nameField.getText();
				if (!FieldVerifier.isValidName(textToServer)) {
					errorLabel.setText("Please enter at least four characters");
					return;
				}

				// Then, we send the input to the server.
				//sendButton.setEnabled(false);
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.greetServer(textToServer,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox
										.setText("Failed to connect to server");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								System.out.println(caught.getMessage());
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								
								
								//DecoratorPanel newAnswerPanel = new DecoratorPanel();
								DisclosurePanel newAnswerPanel = new DisclosurePanel(AIOS.completeLine(textToServerLabel.getText()));
								newAnswerPanel.setAnimationEnabled(true);
								Label textToServerLbl = new Label(textToServerLabel.getText());
								HTML serverResponseLl = new HTML();
								serverResponseLl
								.removeStyleName("serverResponseLabelError");
								serverResponseLl.setHTML(result);
//						dialogBox.center();
//						closeButton.setFocus(true);
								
								Widget innerVPanel = null;
								if(num%3 == 0) {
									innerVPanel = new YouTubeEmbeddedPlayer("hqXUKxJiDls");
									innerVPanel.setWidth("427px");
									innerVPanel.setHeight("320px");
									((YouTubeEmbeddedPlayer)innerVPanel).embed(); 
								} else if (num%2 == 1) {
									innerVPanel = new VerticalPanel();
									innerVPanel.setWidth("600px");
									innerVPanel.addStyleName("dialogVPanel");
									((VerticalPanel)innerVPanel).add(new HTML("<b>Sending inquery to the server:</b>"));
									((VerticalPanel)innerVPanel).add(textToServerLbl);
									((VerticalPanel)innerVPanel).add(new HTML("<br><b>Server replies:</b>"));
									((VerticalPanel)innerVPanel).add(serverResponseLl);
									((VerticalPanel)innerVPanel).setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
								} else {
									innerVPanel = new YouTubeEmbeddedPlayer("NugRZGDbPFU");
									innerVPanel.setWidth("427px");
									innerVPanel.setHeight("320px");
									((YouTubeEmbeddedPlayer)innerVPanel).embed();
								}
								
									
								num++;
								
								newAnswerPanel.add(AIOS.getCenteredHorizontalAlignment(innerVPanel,HasVerticalAlignment.ALIGN_MIDDLE));
								answersPanel.add(newAnswerPanel);
								newAnswerPanel.setOpen(true);
								scrollPanel.scrollToBottom();
							}
						});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
	}
	
	private static Widget getCenteredHorizontalAlignment(Widget widget, VerticalAlignmentConstant vAlign) {
		FlexTable wrapper = new FlexTable();
		wrapper.setSize("100%", "100%");
		wrapper.setWidget(0, 0, widget);
		wrapper.getFlexCellFormatter().setVerticalAlignment(0, 0, vAlign);
		wrapper.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
		return wrapper;
	}
	
	private static String completeLine(String txt) {
		int i=0;
		if (txt != null) {
			i=txt.length();
			txt+=" ";
		}
		for (; i<90; i++) {
			txt += "_";
		}
		return txt;
	}
}
